<template>
	<a-modal v-bind="optionDialog">
		<div v-if="!confirmFinish">房间物业交割单批量查询确认中，若操作取消，已确认房间的数据将不会保存，请耐心等候!</div>
		<div v-else>
			<template v-if="$props.isSettlement">
				<p>房间物业交割单已全部确认，操作保存即可查看。</p>
				<p>账单已更新，还请重新核对账单明细!</p>
			</template>
			<template v-else>
				<p>房间物业交割单已全部确认，操作保存即可查看。</p>
			</template>
		</div>
		<a-row v-for="(item, index) in unconfirmedList" :key="index" :gutter="[0, 1]">
			<a-space v-if="0 === item.confirmStatus" :size="10">
				<a>{{ item.fullAddress }} 确认中</a>
				<loading-outlined v-color="{color: 'green'}" />
			</a-space>
			<a-space v-else-if="1 === item.confirmStatus" :size="10">
				<a>{{ item.fullAddress }} 确认成功</a>
				<check-outlined v-color="{color: 'green'}" />
			</a-space>
			<a-space v-else :size="10">
				<a>{{ item.fullAddress }} 确认失败</a>
				<close-outlined v-color="{color: 'error'}" />
			</a-space>
		</a-row>
		<template #footer>
			<a-button @click.stop="optionDialog.onCancel">取消</a-button>
			<a-button v-if="confirmFinish" type="primary" @click="submit">确定</a-button>
		</template>
	</a-modal>
</template>

<script lang="ts" setup>
	import {ref, reactive, toRef, watch, onBeforeMount, computed} from 'vue'
	import XEUtils from 'xe-utils'
	import {LoadingOutlined, CheckOutlined, CloseOutlined} from '@ant-design/icons-vue'
	import {defaultMeters} from '@/interface/contract'
	import {getHouseDeliveryGetNoe, houseSetting} from '@/api/contract'
	import {queryDeviceOnlineStatus} from '@/api/device'
	import settingApi from 'yuxin-base/src/api/setting-api'

	const props = defineProps<{
		visible: boolean
		enterPriseContractList: Array<any>
		/** 是否结算 */
		isSettlement: boolean
	}>()
	const emits = defineEmits(['update:visible', 'close'])
	const optionDialog = reactive({
		width: 500,
		title: '退房交割单批量确认',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		class: 'batch-delivery-dialog',
		visible: toRef(props, 'visible'),
		bodyStyle: {
			paddingTop: '10px',
			paddingBottom: '10px',
			maxHeight: '500px',
			overflowY: 'auto'
		},
		onCancel() {
			emits('update:visible', false)
		}
	})

	// 未确认的房间
	const unconfirmedList = ref<Array<any>>([])

	const confirmFinish = computed(() => {
		return !unconfirmedList.value.filter(i => 0 === i.confirmStatus).length
	})

	const getMoneyByID = (energyDictArrList, id) => {
		const feeSubject = energyDictArrList.find(o => o.feeSubjectId === id) || {}
		return parseFloat(feeSubject.price || 0)
	}
	const feeSubject = ref<any>([])
		const getID = id => {
		return feeSubject.value.find(o => o.id === id).name
	}

	const getDicList = async() => {
		// 获取费用科目列表
		await settingApi.getDicListByLabelAll('FEESUBJECT@ENERGY').then(({data}) => {
			feeSubject.value = data[0].metaList
					})
	}
	// 获取当个房间的退租交割单
	const getDelivery = row => {
		const modelRef: any = {
			comment: '',
			attachments: JSON.stringify([]),
			articles: [],
			meters: defaultMeters(),
			id: '',
			meterReadRecordDtos: []
		}
		const {contractId} = row
		let params = {
			id: contractId,
			type: 1
			}
		return new Promise<any>((resolve, reject) => {
			getHouseDeliveryGetNoe(params)
				.then((res: any) => {
					if (res.data) {
						modelRef.id = res.data.id || null
						modelRef.comment = res.data.comment || ''
						modelRef.articles = res.data.articles || []
					}
				})
				.finally(() => {
					if (contractId) {
						houseSetting(contractId)
							.then(async res => {
								// 能耗预警
								const earlyData = res.data?.deviceEnergyWarnings || []
								// 后付费能耗读数
								const postpaData = res.data?.deviceLastReadRecords || []
								// 预付费能耗读数
								modelRef.meterReadRecordDtos = res.data?.meterReadRecords || []
								// 能耗费信息配置
								const energyDictArrList = res.data?.energyCostRoomSettings || []
								// 如果有预警就是确认失败 需要回到页面手动去打开退租弹窗
								const meterRecord = [...modelRef.meterReadRecordDtos,...postpaData]
								const hasEmptyAmount = modelRef.meterReadRecordDtos.some(e => !e.amount) || postpaData.some(e => !e.lastRead || !e.firstRead)
								const deviceIds = meterRecord.map(e => e.deviceId)

								let hasOffLineDevice = false
								// if (deviceIds.length) {
								// 	const {data} = await queryDeviceOnlineStatus(deviceIds)
								// 	hasOffLineDevice = deviceIds.some(id => Number(data[id]) !== 1)
								// }
								const handleSetPostEnergyDictArrs = () => {
									let energyDictArrs:any = []
											//后付费
									if (postpaData.length) {
										for (let o of postpaData) {
																						let item = {
												amount: parseFloat(((o.lastRead - o.firstRead) * getMoneyByID(energyDictArrList,o.feeSubjectId)).toFixed(2)),
												beginDate: o.beginDate,
												endDate: o.endDate,
												feeDirection: 1,
												feeSubjectId: o.feeSubjectId,
												feeSubjectName: getID(o.feeSubjectId),
												id: o.id,
												energyWarningId: o.id,
												notOccurredMoney: parseFloat(((o.lastRead - o.firstRead) * getMoneyByID(energyDictArrList,o.feeSubjectId)).toFixed(2)),
												lastRead: o.lastRead,
												firstRead: o.firstRead,
												deviceId: o.deviceId,
												deviceType: o.deviceType
											}
											energyDictArrs.push(item)
										}
									}
									return energyDictArrs
								}
								if (earlyData.length ||  hasEmptyAmount || hasOffLineDevice) {
									row.confirmStatus = 2
								} else {
									// 确认成功
									row.confirmStatus = 1
									modelRef.earlyData = []
									modelRef.energyDictArr = handleSetPostEnergyDictArrs()
								}
							})
							.finally(() => {
								row.modelRef = modelRef
								resolve(modelRef)
							})
					}
				})
		})
	}

	// 队列形式 不一次性请求
	const queueReq = (list: Array<any>) => {
		let index = 0
		const max = list.length
		let confirm: any = (row: any) => {
			getDelivery(row).then(res => {
				index++
				if (index < max) {
					confirm(list[index])
				} else {
					confirm = null
					return
				}
			})
		}
		confirm(list[index])
	}

	// 重置
	const resetData = () => {
		unconfirmedList.value = []
	}

	// 提交
	const submit = () => {
		optionDialog.onCancel()
		emits('close', XEUtils.clone(unconfirmedList.value, true))
	}
	onBeforeMount(async() =>{
		await getDicList()

	})
	// 定义状态confirmStatus(0 未确认 1 确认成功 2 确认失败)
	watch(
		() => props.visible,
		async newVal => {
			if (newVal) {
				await getDicList()
				resetData()
				const enterPriseContractList = XEUtils.clone(props.enterPriseContractList || [], true)
				// disabled的为未确认的
							unconfirmedList.value = enterPriseContractList.filter(i => i.disabled).map(i => ({...i, confirmStatus: 0}))
				setTimeout(() => {

					if (unconfirmedList.value.length) queueReq(unconfirmedList.value)
				}, 600);
			}
		}
	)
</script>

<style lang="less" scoped></style>
